package com.hivekion.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hivekion.common.entity.vo.LoginUser;
import com.hivekion.common.security.SecurityUtils;
import com.hivekion.common.uuid.IdUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MetaHandler implements MetaObjectHandler {
      private static final Logger logger = LoggerFactory.getLogger(MetaHandler.class);

      @Override
      public void insertFill(MetaObject metaObject) {
	    LoginUser userEntity = SecurityUtils.getCurrentLoginUser();
	    this.setFieldValByName("id", IdUtils.simpleUUID(), metaObject);
	    this.setFieldValByName("createTime", new Date(), metaObject);
	    if (userEntity != null) {
		  this.setFieldValByName("createUserId", userEntity.getUserId(), metaObject);
		  this.setFieldValByName("createUserName", userEntity.getUsername(), metaObject);
	    }
      }

      @Override
      public void updateFill(MetaObject metaObject) {
	    LoginUser userEntity = SecurityUtils.getCurrentLoginUser();
	    this.setFieldValByName("updateTime", new Date(), metaObject);
	    if (userEntity != null) {
		  this.setFieldValByName("updateUserId", userEntity.getUserId(), metaObject);
		  this.setFieldValByName("updateUserName", userEntity.getUsername(), metaObject);
	    }
      }
}
